package org.nood.iptv.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.PlaybackParameters;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.source.dash.DashMediaSource;
import com.google.android.exoplayer2.source.dash.DefaultDashChunkSource;
import com.google.android.exoplayer2.source.hls.HlsMediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.ui.SimpleExoPlayerView;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.nood.iptv.MyApplication;
import org.nood.iptv.R;
import org.nood.iptv.adapter.RecommendListAdapter;
import org.nood.iptv.entity.MediaItem;
import org.nood.iptv.entity.RecommendItem;
import org.nood.iptv.iptv.TvSend;
import org.nood.iptv.utils.Contants;
import org.nood.iptv.utils.DateUtils;
import org.nood.iptv.utils.DensityUtils;
import org.nood.iptv.utils.LogUtils;
import org.nood.iptv.utils.NetworkUtil;
import org.nood.iptv.utils.Utils;
import org.nood.iptv.utils.network.NetSpeed;
import org.nood.iptv.utils.network.NetSpeedTimer;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 点播播放器
 *
 * @author Noodlewar
 * @date 2017/10/25
 */
public class VodPlayer extends AppCompatActivity implements View.OnClickListener, Handler.Callback {

    /**
     * 视频进度的更新
     */
    private static final int PROGRESS = 1;
    /**
     * 隐藏控制面板
     */
    private static final int HIDE_MEDIA_CONTROLLER = 2;
    /**
     * 显示当前网速
     */
    private static final int SHOW_NET_SPEED = 3;
    /**
     * 全屏
     */
    private static final int FULL_SCREEN = 1;
    /**
     * 默认
     */
    private static final int DEFAULT_SCREEN = 2;
    @BindView(R.id.simple_exo_player_view)
    SimpleExoPlayerView simpleExoPlayerView;
    private Uri uri;
    /**
     * 视频播放页面布局
     */
    @BindView(R.id.ll_video)
    LinearLayout llVideo;
    @BindView(R.id.ll_media_msg)
    LinearLayout llMediaMsg;
    @BindView(R.id.btn_media_msg)
    Button btnMediaMsg;
    @BindView(R.id.tv_media_dpi)
    TextView tvMediaDpi;
    @BindView(R.id.tv_media_mime_type)
    TextView tvMediaMimeType;
    @BindView(R.id.tv_media_network)
    TextView tvMediaNetwork;
    @BindView(R.id.tv_media_netspeed)
    TextView tvMediaNetspeed;
    @BindView(R.id.sb_voice)
    SeekBar sbVoice;
    @BindView(R.id.btn_projector)
    Button btnProjector;
    @BindView(R.id.media_control)
    RelativeLayout mediaControl;
    @BindView(R.id.tv_current_time)
    TextView tvCurrentTime;
    @BindView(R.id.sb_video)
    SeekBar videoSeekBar;
    @BindView(R.id.tv_duration)
    TextView tvDuration;
    @BindView(R.id.btn_exit)
    Button btnExit;
    @BindView(R.id.btn_video_pre)
    Button btnVideoPre;
    @BindView(R.id.btn_video_start_pause)
    Button btnVideoStartPause;
    @BindView(R.id.btn_video_next)
    Button btnVideoNext;
    @BindView(R.id.btn_video_switch_screen)
    Button btnVideoSwitchScreen;
    @BindView(R.id.ll_loading)
    LinearLayout llLoading;
    @BindView(R.id.rl1)
    RelativeLayout rl1;
    @BindView(R.id.rl2)
    RelativeLayout rl2;
    @BindView(R.id.ll1)
    LinearLayout ll1;
    @BindView(R.id.ll2)
    LinearLayout ll2;
    @BindView(R.id.show_introduce)
    ImageView showIntroduce;
    /**
     * 播放次数
     */
    @BindView(R.id.play_time)
    TextView playTime;
    /**
     * 推荐列表
     */
    @BindView(R.id.recommend_list)
    ListView recommend_list;
    /**
     * 退出当前页
     */
    @BindView(R.id.back_btn)
    ImageView back_btn;
    /**
     * 点播详情页标题
     */
    @BindView(R.id.tv_toolbar_title)
    TextView tvToolbarTitle;
    /**
     * 标题栏
     */
    @BindView(R.id.main_toolbar)
    Toolbar main_toolbar;
    @BindView(R.id.directors)
    TextView directors;
    @BindView(R.id.actors)
    TextView actors;
    @BindView(R.id.description)
    TextView description;
    /**
     * 播放布局
     */
    @BindView(R.id.play_pager)
    RelativeLayout rl;
    //传入的视频列表
    private List<MediaItem> mediaItems;
    //要播放的列表中的具体位置
    private int position;
    //定义手势识别器
    private GestureDetector detector;
    //是否显示控制面板
    private boolean isShowMediaController = false;
    //是否为全屏
    private boolean isFullScreen = false;
    //屏幕的宽
    private int screenWidth = 0;
    //屏幕的高
    private int screenHeight = 0;

    /**
     * 视频真实的宽和高
     */
    private int videoWidth;
    private int videoHeight;

    /**
     * 调节声音
     */
    private AudioManager audioManager;
    /**
     * 当前音量
     */
    private int currentVolume;
    /**
     * 等级0-15
     * 最大音量
     */
    private int maxVolume;
    private boolean isMute = false;
    /**
     * 是否为网络URI
     */
    private boolean isNetUri;
    /**
     * 是否显示简介
     */
    private boolean isShowIntroduce = true;
    /**
     * 视频资源ID
     */
    private String mediaId;

    private SimpleExoPlayer player;
    String url;
    MediaSource videoSource;
    private DefaultDataSourceFactory dataSourceFactory;
    private DefaultExtractorsFactory extractorsFactory;
    private Handler mainHandler;
    private long beginTime;

    private NetSpeedTimer netSpeedTimer;

    private static final DefaultBandwidthMeter BANDWIDTH_METER = new DefaultBandwidthMeter();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DensityUtils.init(this);

        initData();

        getData();

        findViews();

        setListener();

        setData();

        Handler netHandler = new Handler(this);
        //创建NetSpeedTimer实例
        netSpeedTimer = new NetSpeedTimer(this, new NetSpeed(), netHandler).setDelayTime(1000).setPeriodTime(2000);
        //在想要开始执行的地方调用该段代码
        netSpeedTimer.startSpeedTimer();
    }


    /**
     * 绑定事件监听
     */
    private void findViews() {
        setContentView(R.layout.activity_vod_player);
        ButterKnife.bind(this);

        btnMediaMsg.setOnClickListener(this);
        btnProjector.setOnClickListener(this);
        btnExit.setOnClickListener(this);
        btnVideoPre.setOnClickListener(this);
        btnVideoStartPause.setOnClickListener(this);
        btnVideoNext.setOnClickListener(this);
        btnVideoSwitchScreen.setOnClickListener(this);
        back_btn.setOnClickListener(this);
        showIntroduce.setOnClickListener(this);

        //设置控制面板
        //vv_video.setMediaController(new MediaController(this));

        //最大音量和SeekBar关联
        sbVoice.setMax(maxVolume);
        //设置当前音量
        sbVoice.setProgress(currentVolume);

        //开始更新网速
        handler.sendEmptyMessage(SHOW_NET_SPEED);

        mainHandler = new Handler();
        DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
        TrackSelection.Factory videoTrackSelectionFactory =
                new AdaptiveTrackSelection.Factory(bandwidthMeter);
        TrackSelector trackSelector =
                new DefaultTrackSelector(videoTrackSelectionFactory);

        player = ExoPlayerFactory.newSimpleInstance(this, trackSelector);

        simpleExoPlayerView.setPlayer(player);
        simpleExoPlayerView.setUseController(false);

        dataSourceFactory = new DefaultDataSourceFactory(this,
                Util.getUserAgent(this, "yourApplicationName"), bandwidthMeter);
        extractorsFactory = new DefaultExtractorsFactory();

        player.addListener(new ExoPlayer.EventListener() {
            @Override
            public void onTimelineChanged(Timeline timeline, Object manifest) {

            }

            @Override
            public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {

            }

            @Override
            public void onLoadingChanged(boolean isLoading) {

            }

            @Override
            public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
                if (playWhenReady) {
                    llLoading.setVisibility(View.GONE);
                }
            }

            @Override
            public void onPlayerError(ExoPlaybackException error) {
                Toast.makeText(VodPlayer.this, "无法播放该视频！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onPositionDiscontinuity() {

            }

            @Override
            public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v == btnMediaMsg) {
            if (llMediaMsg.isShown()) {
                llMediaMsg.setVisibility(View.INVISIBLE);
            } else {
                llMediaMsg.setVisibility(View.VISIBLE);
            }

            Format format = player.getVideoFormat();

            tvMediaDpi.setText("分辨率： " + format.width + "*" + format.height);
            tvMediaMimeType.setText("类型： " + format.sampleMimeType);
            tvMediaNetwork.setText("网络：" + NetworkUtil.getNetWorkName(VodPlayer.this));

            Log.i("MEDIA-INFO", player.getVideoFormat().bitrate + "");
        } else if (v == btnProjector) {
            projectVod();
        } else if (v == btnExit) {
            // Handle clicks for btnExit
            finish();
        } else if (v == btnVideoPre) {
            // Handle clicks for btnVideoPre
            playPreVideo();
        } else if (v == btnVideoStartPause) {
            startAndPause();
        } else if (v == btnVideoNext) {
            // Handle clicks for btnVideoNext
            playNextVideo();
        } else if (v == btnVideoSwitchScreen) {
            // Handle clicks for btnVideoSwitchScreen
            switchScreen();
        } else if (v == back_btn) {
            finish();
        } else if (v == showIntroduce) {
            if (!isShowIntroduce) {
                rl2.setVisibility(View.VISIBLE);
                showIntroduce.setImageResource(R.drawable.up_arrow);
                isShowIntroduce = true;
            } else {
                rl2.setVisibility(View.GONE);
                showIntroduce.setImageResource(R.drawable.down_arrow);
                isShowIntroduce = false;
            }
        }

        handler.removeMessages(HIDE_MEDIA_CONTROLLER);
        handler.sendEmptyMessageDelayed(HIDE_MEDIA_CONTROLLER, 3000);
    }

    private void startAndPause() {
        // Handle clicks for btnVideoStartPause
        if (player.getPlayWhenReady()) {
            //视频在播放,设置为暂停,按钮设置为播放
            player.setPlayWhenReady(false);
            btnVideoStartPause.setBackgroundResource(R.drawable.btn_video_start_selector);
        } else {
            //视频暂停,设置为播放,按钮设置为暂停
            player.setPlayWhenReady(true);
            btnVideoStartPause.setBackgroundResource(R.drawable.btn_video_pause_selector);
        }
    }

    /**
     * 播放上一个视频
     */
    private void playPreVideo() {
        if (mediaItems != null && mediaItems.size() > 0) {
            //播放上一个视频
            position--;
            if (position >= 0) {

                //ll_loading.setVisibility(View.VISIBLE);

                MediaItem mediaItem = mediaItems.get(position);
                isNetUri = Utils.isNetUri(mediaItem.getData());
                //vv_video.setVideoPath(mediaItem.getData());
                //设置按钮状态
                setButtonStatus();
            }
        } else if (uri != null) {
            //设置按钮状态--上一个和下一个按钮设置为灰色并且不可以点击
            setButtonStatus();
        }
    }

    /**
     * 播放下一个视频
     */
    private void playNextVideo() {
        if (mediaItems != null && mediaItems.size() > 0) {
            //播放下一个
            position++;
            if (position < mediaItems.size()) {

                //ll_loading.setVisibility(View.VISIBLE);

                MediaItem mediaItem = mediaItems.get(position);
                isNetUri = Utils.isNetUri(mediaItem.getData());
                //vv_video.setVideoPath(mediaItem.getData());

                //设置按钮状态
                setButtonStatus();
            }
        } else if (uri != null) {
            //上一个和下一个按钮设置为灰色并且不可以点击
            setButtonStatus();
        }
    }

    private void setButtonStatus() {
        if (mediaItems != null && mediaItems.size() > 0) {
            if (mediaItems.size() == 1) {
                //两个按钮都设置为灰色
                setEnable(false);
            } else if (mediaItems.size() == 2) {
                if (position == 0) {
                    btnVideoPre.setBackgroundResource(R.drawable.btn_pre_gray);
                    btnVideoPre.setEnabled(false);

                    btnVideoNext.setBackgroundResource(R.drawable.btn_video_next_selector);
                    btnVideoNext.setEnabled(false);
                } else if (position == mediaItems.size() - 1) {
                    btnVideoNext.setBackgroundResource(R.drawable.btn_next_gray);
                    btnVideoNext.setEnabled(false);

                    btnVideoPre.setBackgroundResource(R.drawable.btn_video_pre_selector);
                    btnVideoPre.setEnabled(true);
                } else {
                    setEnable(true);
                }
            } else {
                if (position == 0) {
                    btnVideoPre.setBackgroundResource(R.drawable.btn_pre_gray);
                    btnVideoPre.setEnabled(false);
                } else if (position == mediaItems.size() - 1) {
                    btnVideoNext.setBackgroundResource(R.drawable.btn_next_gray);
                    btnVideoNext.setEnabled(false);
                } else {
                    setEnable(true);
                }
            }
        } else if (uri != null) {
            //两个按钮都设置为灰色
            btnVideoPre.setBackgroundResource(R.drawable.btn_pre_gray);
            btnVideoPre.setEnabled(false);
            btnVideoNext.setBackgroundResource(R.drawable.btn_next_gray);
            btnVideoNext.setEnabled(false);
        }
    }

    private void setEnable(boolean flag) {
        if (flag) {
            btnVideoPre.setBackgroundResource(R.drawable.btn_video_pre_selector);
            btnVideoPre.setEnabled(true);
            btnVideoNext.setBackgroundResource(R.drawable.btn_video_next_selector);
            btnVideoNext.setEnabled(true);
        } else {
            btnVideoPre.setBackgroundResource(R.drawable.btn_pre_gray);
            btnVideoPre.setEnabled(false);
            btnVideoNext.setBackgroundResource(R.drawable.btn_next_gray);
            btnVideoNext.setEnabled(false);
        }
    }

    private void setData() {
        if (mediaItems != null && mediaItems.size() > 0) {
            MediaItem mediaItem = mediaItems.get(position);
            //设置视频的名称
            isNetUri = Utils.isNetUri(mediaItem.getData());
            //vv_video.setVideoPath(mediaItem.getData());
        } else if (uri != null) {
            //设置视频的名称
            isNetUri = Utils.isNetUri(uri.toString());
            //vv_video.setVideoURI(uri);
        }
        setButtonStatus();
    }


    private void initData() {
        //实例化手势识别器，并重写双击，单击，长按
        detector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public void onLongPress(MotionEvent e) {
                super.onLongPress(e);
                startAndPause();
            }

            @Override
            public boolean onDoubleTap(MotionEvent e) {
                switchScreen();
                return super.onDoubleTap(e);
            }

            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                if (isShowMediaController) {
                    //隐藏
                    hideMediaController();
                    //把隐藏消息移除
                    handler.removeMessages(HIDE_MEDIA_CONTROLLER);
                } else {
                    //显示
                    showMediaController();
                    //发消息隐藏
                    handler.sendEmptyMessageDelayed(HIDE_MEDIA_CONTROLLER, 3000);
                }
                return super.onSingleTapConfirmed(e);
            }
        });

        //获取音量
        audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    }

    private void getData() {
        //获取播放地址
        // uri = getIntent().getData();// 文件夹，图片浏览器
        //uri = Uri.parse("http://ivi.bupt.edu.cn/hls/cctv1hd.m3u8");
        //uri = Uri.parse("http://125.88.92.230:30001/PLTV/88888905/224/3221226931/00000100000000060000000000554902_0.smil");
        //uri = Uri.parse("http://vf2.mtime.cn/Video/2017/05/06/mp4/170506082411224771.mp4");
        //uri = Uri.parse("http://125.88.92.230:30001/PLTV/88888956/224/3221227674/index.m3u8");
        mediaId = getIntent().getStringExtra("mediaId");
        beginTime = getIntent().getLongExtra("beginTime", 0);
        getDataGetByOkhttpUtils(mediaId);
        //uri = Uri.parse("http://vf2.mtime.cn/Video/2017/05/06/mp4/170506082411224771.mp4");
        //url = "http://172.19.120.34:8888/movie_round1/" + mediaId + "/" + mediaId + ".m3u8";
        // uri = Uri.parse("http://172.19.120.61:8080/Odetojoy_1/Odetojoy_1.m3u8");
        //uri = Uri.parse("http://172.19.120.61:8080/ArcSoft_4k_1/ArcSoft_4k_1.m3u8");

        // 华为点播测试地址
        // uri = Uri.parse("http://192.168.204.208/88888888/16/20170825/268435477/index.m3u8?servicetype=0");

        //mediaItems = (List<MediaItem>) getIntent().getSerializableExtra("videolist");
        //LogUtils.i(mediaItems.toString());
        position = getIntent().getIntExtra("position", 0);
    }

    private void switchScreen() {
        /*if (isFullScreen) {
            //默认
            setVideoType(DEFAULT_SCREEN);
        } else {
            //全屏
            setVideoType(FULL_SCREEN);
        }*/
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    private void setVideoType(int screenType) {
        // 获取屏幕的宽和高
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        screenWidth = metrics.widthPixels;
        screenHeight = metrics.heightPixels;

        switch (screenType) {
            // 全屏
            case FULL_SCREEN:
                //设置视频画面的大小
                //vv_video.setVideoSize(screenWidth, screenHeight);
                //设置按钮的状态-默认
                btnVideoSwitchScreen.setBackgroundResource(R.drawable.btn_video_switch_default_screen_selector);
                isFullScreen = true;
                break;
            // 默认
            case DEFAULT_SCREEN:
                //设置视频画面的大小

                //视频真实的宽和高
                int mVideoWidth = videoWidth;
                int mVideoHeight = videoHeight;

                int width = screenWidth;
                int height = screenHeight;
                if (mVideoWidth * height < width * mVideoHeight) {
                    width = height * mVideoWidth / mVideoHeight;
                } else if (mVideoWidth * height > width * mVideoHeight) {
                    height = width * mVideoHeight / mVideoWidth;
                }
                //vv_video.setVideoSize(width, height);
                //设置按钮的状态-全屏
                btnVideoSwitchScreen.setBackgroundResource(R.drawable.btn_video_switch_default_screen_selector);
                isFullScreen = false;
                break;
            default:
                break;
        }
    }

    private void setListener() {
        //准备好的监听
        //vv_video.setOnPreparedListener(new MyOnPreparedListener());

        //播放出错的监听
        //vv_video.setOnErrorListener(new MyOnErrorListener());

        //播放完成的监听
        //vv_video.setOnCompletionListener(new MyOnCompletionListener());

        //设置SeekBar状态变化的监听
        videoSeekBar.setOnSeekBarChangeListener(new VideoOnSeekBarChangeListener());

        sbVoice.setOnSeekBarChangeListener(new VolumeOnSeekBarChangeListener());

    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case NetSpeedTimer.NET_SPEED_TIMER_DEFAULT:
                String speed = (String) msg.obj;
                //打印你所需要的网速值，单位默认为kb/s
                tvMediaNetspeed.setText("网速：" + speed);
                break;
            default:
                break;
        }
        return false;
    }

    private class VolumeOnSeekBarChangeListener implements SeekBar.OnSeekBarChangeListener {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                isMute = progress <= 0;
                updateVolume(progress, isMute);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }

    }

    /**
     * 设置音量大小
     *
     * @param progress 音量进度
     */
    private void updateVolume(int progress, boolean isMute) {
        if (isMute) {
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
            sbVoice.setProgress(0);
        } else {
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
            sbVoice.setProgress(progress);
            currentVolume = progress;
        }
    }

    private class VideoOnSeekBarChangeListener implements SeekBar.OnSeekBarChangeListener {
        /**
         * 当手指滑动的时候，会引起SeekBar进度变化，会回调该方法
         *
         * @param progress 当前进度
         * @param fromUser 进度条变化如果是用户引起的true，不是则为false
         */
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                player.seekTo(progress);
            }
        }

        /**
         * 当手指触碰的时候回调该方法
         */
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            handler.removeMessages(HIDE_MEDIA_CONTROLLER);
        }

        /**
         * 当手指离开的时候回调该方法
         */
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            handler.sendEmptyMessageDelayed(HIDE_MEDIA_CONTROLLER, 3000);
        }

    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SHOW_NET_SPEED:
                    //获取网速
                    String netSpeed = Utils.getNetSpeed(VodPlayer.this);

                    //显示网络速度
                    //tv_loading_net_speed.setText("玩命加载中..." + netSpeed);
                    //tv_net_speed.setText("缓冲中..." + netSpeed);

                    //每两秒更新一次
                    handler.removeMessages(SHOW_NET_SPEED);
                    handler.sendEmptyMessageDelayed(SHOW_NET_SPEED, 2000);

                    break;
                case HIDE_MEDIA_CONTROLLER:
                    //隐藏控制面板
                    hideMediaController();
                    break;
                case PROGRESS:
                    //得到当前视频的播放进度
                    int currentPosition = (int) player.getCurrentPosition();
                    videoSeekBar.setProgress(currentPosition);

                    //更新文本播放进度
                    tvCurrentTime.setText(Utils.stringForTime(currentPosition));

                    //缓冲进度的更新
                    if (isNetUri) {
                        //只有网络资源才有缓冲
                        int buffer = player.getBufferedPercentage();
                        int totalBuffer = videoSeekBar.getMax();
                        int secondaryProgress = totalBuffer / 100;
                        videoSeekBar.setSecondaryProgress(secondaryProgress);
                    } else {
                        //本地视频没有缓冲
                        videoSeekBar.setSecondaryProgress(0);
                    }

                    //每秒更新一次
                    handler.removeMessages(PROGRESS);
                    handler.sendEmptyMessageDelayed(PROGRESS, 1000);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        // 移除所有的消息
        handler.removeCallbacksAndMessages(null);
        player.release();
        LogUtils.e("VodPlayActivity is destroyed");
        super.onDestroy();
        if (null != netSpeedTimer) {
            netSpeedTimer.stopSpeedTimer();
        }
    }

    private float startY;
    /**
     * 屏幕的高
     */
    private float touchRang;
    /**
     * 当一按下的音量
     */
    private int mVol;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //把事件传递给手势识别器
        detector.onTouchEvent(event);

        switch (event.getAction()) {
            // 手指按下
            case MotionEvent.ACTION_DOWN:
                // 按下时记录值
                startY = event.getY();
                mVol = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                touchRang = Math.min(screenHeight, screenWidth);
                handler.removeMessages(HIDE_MEDIA_CONTROLLER);
                break;
            // 手指移动
            case MotionEvent.ACTION_MOVE:
                // 移动的记录相关值
                float endY = event.getY();
                float distanceY = startY - endY;
                // 改变声音 = （滑动屏幕距离 : 总距离）* 音量最大值
                float delta = distanceY / touchRang * maxVolume;
                // 最终声音 = 原来音量 + 改变声音
                int volume = (int) Math.min(maxVolume, Math.max(0, mVol + delta));
                if (delta != 0) {
                    isMute = false;
                    updateVolume(volume, isMute);
                }
                break;
            // 手指离开
            case MotionEvent.ACTION_UP:
                handler.sendEmptyMessageDelayed(HIDE_MEDIA_CONTROLLER, 3000);
                break;
            default:
                break;
        }
        return super.onTouchEvent(event);
    }

    /**
     * 隐藏控制面板
     */
    private void hideMediaController() {
        mediaControl.setVisibility(View.GONE);
        isShowMediaController = false;
    }

    /**
     * 显示控制面板
     */
    private void showMediaController() {
        llMediaMsg.setVisibility(View.INVISIBLE);
        mediaControl.setVisibility(View.VISIBLE);
        isShowMediaController = true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            currentVolume--;
            updateVolume(currentVolume, false);
            handler.removeMessages(HIDE_MEDIA_CONTROLLER);
            handler.sendEmptyMessageDelayed(HIDE_MEDIA_CONTROLLER, 3000);
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            currentVolume++;
            updateVolume(currentVolume, false);
            handler.removeMessages(HIDE_MEDIA_CONTROLLER);
            handler.sendEmptyMessageDelayed(HIDE_MEDIA_CONTROLLER, 3000);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // 横屏竖屏判断
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            setSystemUiHide();// 隐藏最上面那一栏
            // 设置视频尺寸
            setVideoType(DEFAULT_SCREEN);
            // 设置为全屏
            setVideoViewScale(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

            main_toolbar.setVisibility(View.GONE);
            ll1.setVisibility(View.GONE);
            ll2.setVisibility(View.GONE);
            rl1.setVisibility(View.GONE);
            rl2.setVisibility(View.GONE);
            // 强制移除半屏状态
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            setSystemUiShow();// 显示最上面那一栏
            // 设置视频尺寸
            setVideoType(DEFAULT_SCREEN);

            ViewGroup.LayoutParams params = llVideo.getLayoutParams();
            params.width = ViewGroup.LayoutParams.MATCH_PARENT;
            params.height = ViewGroup.LayoutParams.MATCH_PARENT;
            llVideo.setLayoutParams(params);

            ViewGroup.LayoutParams params1 = rl.getLayoutParams();
            params1.width = ViewGroup.LayoutParams.MATCH_PARENT;
            params1.height = DensityUtils.dp2px(240);
            rl.setLayoutParams(params1);

            main_toolbar.setVisibility(View.VISIBLE);
            ll1.setVisibility(View.VISIBLE);
            ll2.setVisibility(View.VISIBLE);
            rl1.setVisibility(View.VISIBLE);
            rl2.setVisibility(View.VISIBLE);

            //强制移除全屏状态
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        }
    }

    /**
     * 隐藏SystemUI
     */
    private void setSystemUiHide() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }

    /**
     * 显示SystemUI
     */
    private void setSystemUiShow() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        }
    }

    /**
     * 设置VideoView的大小
     */
    private void setVideoViewScale(int width, int height) {
        ViewGroup.LayoutParams params = llVideo.getLayoutParams();
        params.width = width;
        params.height = height;
        llVideo.setLayoutParams(params);

        ViewGroup.LayoutParams params1 = rl.getLayoutParams();
        params1.width = width;
        params1.height = height;
        rl.setLayoutParams(params1);
    }

    /**
     * 返回事件
     */
    @Override
    public void onBackPressed() {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            super.onBackPressed();
        }
    }

    /**
     * 使用okhttp-utils的get请求网络文本数据
     */
    public void getDataGetByOkhttpUtils(String mediaId) {
        String url = Contants.BASE_URL + "client/video/" + mediaId;
        LogUtils.i(url);
        OkGo.<String>get(url).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (response.body() != null && !"".equals(response.body())) {
                    JSONObject object = JSON.parseObject(response.body());
                    String videoDetailInfo = object.getString("videoDetailInfo");
                    if (videoDetailInfo == null) {
                        return;
                    }
                    JSONObject videoDetailObj = JSON.parseObject(videoDetailInfo);

                    String playURL;

                    Object currentEpisodeNumObj = videoDetailObj.get("currentEpisodeNum");
                    // 电视剧
                    if (currentEpisodeNumObj != null) {
                        JSONArray episodeInfoList = JSON.parseArray(videoDetailObj.getString("episodeInfoList"));
                        String obj = episodeInfoList.getString(Integer.parseInt(currentEpisodeNumObj.toString()));
                        JSONObject videoDetail = JSON.parseObject(obj);

                        tvToolbarTitle.setText(videoDetail.getString("episodeTitle"));
                        directors.setText("导演：" + videoDetailObj.getString("directors"));
                        actors.setText("演员：" + videoDetailObj.getString("actors"));
                        description.setText("简介：" + videoDetailObj.getString("description"));
                        // 设置视频时长
                        String length = videoDetail.getString("length");
                        length = length.substring(0, length.length() - 3);
                        tvDuration.setText(length);
                        videoSeekBar.setMax(DateUtils.convertStringToTime(length));
                        playURL = videoDetail.getString("playURL");
                        getUserRecommend(videoDetailObj.getString("tags"), "110");
                    } else { //其他
                        tvToolbarTitle.setText(videoDetailObj.getString("title"));
                        directors.setText("导演：" + videoDetailObj.getString("directors"));
                        actors.setText("演员：" + videoDetailObj.getString("actors"));
                        description.setText("简介：" + videoDetailObj.getString("description"));

                        String types = videoDetailObj.getString("tags");
                        getUserRecommend(types, "100");

                        // 设置视频时长
                        String length = videoDetailObj.getString("length");
                        length = length.substring(0, length.length() - 3);
                        tvDuration.setText(length);
                        videoSeekBar.setMax(DateUtils.convertStringToTime(length));
                        playURL = videoDetailObj.getString("playURL");
                    }

                    //playURL = "https://storage.googleapis.com/wvmedia/clear/hevc/tears/tears.mpd";
                    //playURL = "http://192.168.209.223/PLTV/88888888/224/3221225611/3221225611.mpd";
                    //playURL = "igmp://239.77.0.244:5146";

                    if (playURL.endsWith(".mpd")) {
                        DataSource.Factory mediaDataSourceFactory = buildDataSourceFactory(true);
                        videoSource = new DashMediaSource(Uri.parse(playURL), buildDataSourceFactory(false), new DefaultDashChunkSource.Factory(mediaDataSourceFactory), mainHandler, null);
                    } else if (playURL.endsWith(".m3u8") || playURL.endsWith((".ts"))) {
                        videoSource = new HlsMediaSource(Uri.parse(playURL), dataSourceFactory, mainHandler, null);
                    } else {
                        videoSource = new ExtractorMediaSource(Uri.parse(playURL),
                                dataSourceFactory, extractorsFactory, null, null);
                    }

                    player.prepare(videoSource);
                    // 跳转到指定播放时间
                    player.seekTo(beginTime * 1000);
                    player.setPlayWhenReady(true);

                    handler.sendEmptyMessage(PROGRESS);
                    handler.sendEmptyMessage(10);
                }
            }
        });
    }

    private DataSource.Factory buildDataSourceFactory(boolean useBandwidthMeter) {
        return ((MyApplication) getApplication())
                .buildDataSourceFactory(useBandwidthMeter ? BANDWIDTH_METER : null);
    }

    /**
     * 点播投屏
     */
    public void projectVod() {
        url = TvSend.buildVodProjectScreenUrl(mediaId);
        OkGo.<String>post(url).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String data = response.body();
                LogUtils.i(data);
                if (data != null && !"".equals(data)) {
                    JSONObject object = JSON.parseObject(data);
                    String resCode = object.getString("res_code");
                    if ("0".equals(resCode)) {
                        // 视频在播放则设置为暂停,按钮设置为播放
                        if (player.getPlayWhenReady()) {
                            player.setPlayWhenReady(false);
                            btnVideoStartPause.setBackgroundResource(R.drawable.btn_video_start_selector);
                        }
                    }
                }
            }
        });
    }

    /**
     * 获取用户推荐数据
     */
    public void getUserRecommend(String types, String iptvType) {
        OkGo.<String>post(Contants.BASE_URL + "client/user/recommend")
                // TODO 用户推荐接口参数用户ID目前写死
                .params("userId", "075500000612")
                .params("types", types)
                .params("iptvType", iptvType)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String data = response.body();
                        LogUtils.i(response.body());
                        if (data != null && !"".equals(data)) {
                            JSONObject object = JSON.parseObject(data);
                            String dataStr = object.getString("data");
                            List<JSONObject> list = JSON.parseArray(dataStr, JSONObject.class);

                            final List<RecommendItem> recommendItems = new ArrayList<>();
                            for (int i = 0; i < 3; i++) {
                                RecommendItem item = new RecommendItem();
                                item.setPosterUrl(Contants.BASE_IMG_URL + list.get(i).getString("picture"));
                                item.setName(list.get(i).getString("name"));
                                item.setContent("主演：" + list.get(i).getString("actors"));
                                item.setIptvCode(list.get(i).getString("iptvCode"));
                                recommendItems.add(item);
                            }
                            recommend_list.setAdapter(new RecommendListAdapter(VodPlayer.this, recommendItems));
                            recommend_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    Intent intent = new Intent(VodPlayer.this, VodPlayer.class);
                                    intent.putExtra("mediaId", recommendItems.get(position).getIptvCode());
                                    VodPlayer.this.startActivity(intent);
                                    VodPlayer.this.finish();
                                }
                            });
                        }
                    }
                });
    }

}
